package com.example.myapplication.model;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class SendMailTask extends AsyncTask<String, Void, String> {

    private Context mContext;

    public SendMailTask(Context context) {
        mContext = context;
    }

    @Override
    protected String doInBackground(String... params) {
        String serverUrl = "http://39.107.92.86:5000/send_email";
        String subject = params[0];
        String body = params[1];
        String result = "";
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(serverUrl + "?subject=" + subject + "&body=" + body);
            urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            result = response.toString();
        } catch (IOException e) {
            Log.e("SendEmailTask", "Error: " + e.getMessage());
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
    }
}
